package win.liumian.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import win.liumian.sso.server.service.TicketService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import static win.liumian.sso.server.util.Constants.SSO_TICKET;

/**
 * @author liumian
 */
@Controller
public class IndexController {


    @Autowired
    public TicketService ticketService;

    @RequestMapping({"index", "/"})
    public String index(@CookieValue(value = SSO_TICKET, required = false) String ssoTicket,
                        @RequestParam(required = false, value = "redirectUrl") String redirectUrl,
                        HttpServletResponse response,
                        RedirectAttributes model) {

        //检测该用户是否已经登录，如果已经登录，那么直接重定向到第三方应用

        if (!StringUtils.isEmpty(ssoTicket) && ticketService.isLegalTicket(ssoTicket)) {
            if (StringUtils.isEmpty(redirectUrl)) {
                return "hello";
            } else {
                model.addAttribute(SSO_TICKET, ssoTicket);
                return "redirect:" + redirectUrl;
            }
        } else {
            destroyCookie(response, SSO_TICKET, ssoTicket);
            return "index";
        }
    }


    /**
     * 销毁cookie
     *
     * @param response
     * @param cookieName cookie名
     * @param ssoTicket  jwt
     */
    private void destroyCookie(HttpServletResponse response, String cookieName, String ssoTicket) {
        Cookie cookie = new Cookie(cookieName, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        //直接注销登录凭证
        if (!StringUtils.isEmpty(ssoTicket)) {
            ticketService.deleteTicket(ssoTicket);
        }

    }

}
